import axios from 'axios';

const PRODUCT_ID = "461323198429807005";
const CLIENT_ID = "1654531991325938240";
const CLIENT_SECRET = "1B2371A951B71755B739CFE76A1673F0E8661A3637DED8EE8C3DAB0A840CFB84";

const TOKEN_URL = 'https://connect-drcn.dbankcloud.cn/agc/apigw/oauth2/v1/token';

class TokenHelper {
    /**
     * 获取华为开放平台的访问令牌
     * @returns {Promise<string>} 返回访问令牌
     */
    async getHuaweiToken() {
        try {
            console.log('开始获取华为开放平台 token');
            const params = {
                useJwt: "1",
                grant_type: "client_credentials",
                client_id: CLIENT_ID,
                client_secret: CLIENT_SECRET
            }

            const response = await axios.post(TOKEN_URL, params, {
                headers: {
                    'Content-Type': 'application/json'
                }
            });

            if (response.data && response.data.access_token) {
                console.log('成功获取华为开放平台 token');
                return response.data.access_token;
            } else {
                throw new Error('获取 token 响应中没有 access_token');
            }
        } catch (error) {
            console.error('获取华为开放平台 token 失败:', error.message);
            if (error.response) {
                console.error('错误详情:', error.response.data);
            }
            throw error;
        }
    }
}

let tokenHelper = new TokenHelper();
export default tokenHelper;

// 使用示例
tokenHelper.getHuaweiToken().then(token => {
    console.log('Token:', token);
}).catch(err => {
    console.error('Error:', err);
});